import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Storage } from '@ionic/storage';
import { PublicCompoentsProvider } from '../public-compoents/public-compoents'

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

/*
  Generated class for the ServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ServiceProvider {
    public baseUrl = "http://second.noyechina.cn/index.php/shop";
    // public baseUrl = "http://two.bjyblkj.cn/index.php/shop";


    constructor(
        public storage: Storage,
        public http: Http,
        public pubCon: PublicCompoentsProvider) {
        console.log('Hello ServiceProvider Provider');
    }

    //将秒数转换成时间
    public stotime(fmt) {
        let unixTimestamp,
            commonTime;
        if (fmt.length == 10) {
            unixTimestamp = new Date(fmt * 1000);
        } else {
            unixTimestamp = new Date(fmt);
        }
        // commonTime = unixTimestamp.toLocaleString();
        commonTime = unixTimestamp.toLocaleTimeString();
        return commonTime;
    };

    public post(url, body) {
        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'
        });
        let options = new RequestOptions({
            headers: headers
        });
        let datas = this.toQueryString(body);

        return new Promise((resolve, reject) => {
            // this.pubCon.showLoading();
            this.http.post(this.baseUrl + url, datas, options)
                .map(res => res.json())
                .subscribe(data => {
                    resolve(data);
                    // this.pubCon.hideLoading();
                }, err => {
                    reject(err)
                })
        })
    };

    private toQueryString(obj) {
        let result = [];
        for (let key in obj) {
            key = encodeURIComponent(key);
            let values = obj[key];
            if (values && values.constructor == Array) {
                let queryValues = [];
                for (let i = 0, len = values.length, value; i < len; i++) {
                    value = values[i];
                    queryValues.push(this.toQueryPair(key, value));
                }
                result = result.concat(queryValues);
            } else {
                result.push(this.toQueryPair(key, values));
            }
        }
        return result.join('&');
    };

    private toQueryPair(key, value) {
        if (typeof value == 'undefined') {
            return key;
        }
        return key + '=' + encodeURIComponent(value === null ? '' : String(value));
    };

}
